package cn.pinyuan.news.service.impl;

import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import cn.pinyuan.news.bean.NewsContent;
import cn.pinyuan.news.mapper.NewsContentMapper;
import cn.pinyuan.news.service.NewsItemPageService;
import freemarker.template.Configuration;
import freemarker.template.Template;
/**
 * FreeMarker模板
 * @author 李文其
 *
 */
@Service
public class NewsItemPageServiceImpl implements NewsItemPageService {

	@Autowired
	public FreeMarkerConfigurer freeMarkerConfigurer;
	
	@Value("${pagedir}")
	private String pagedir;
	
	@Autowired
	private NewsContentMapper newsContentMapper;
	
	public boolean getNewsItemPageHtml(long newsId) {
		Configuration configuration = freeMarkerConfigurer.getConfiguration();
		try {
			// 读取模板文件
			Template template = configuration.getTemplate("news.ftl");
			// 创建数据模型
			Map dateModel = new HashMap<>();
			
			// 添加商品数据
			NewsContent newsContent = newsContentMapper.selectByPrimaryKey((int)newsId);
			
			dateModel.put("news", newsContent);
			
			Writer out = new FileWriter(pagedir+newsId+".html");
			
			template.process(dateModel, out);
			
			out.close();
			
			return true;
			
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

}
